package cn.mengfly.testnrz.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.io.Closeable;
import java.io.IOException;

/**
 * 生成分布式Id
 *
 * @author Mengfly
 */
public class IdMaker implements Closeable {

    private final CuratorFramework client;

    public IdMaker(String connectStr) {
        client = ClientFactory.createSimple(connectStr);
        client.start();
    }

    private String createSeqNode(String pathPrefix) {
        try {
            // 创建了一个ZNode顺序节点
            // 为了避免Zookeeper的顺序节点暴增，建议创建以后删除创建的节点
            return client.create()
                    .creatingParentContainersIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(pathPrefix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String makeId(String nodeName) {
        String str = createSeqNode(nodeName);
        if (str == null) {
            return null;
        }
        // 取得Zookeeper节点的末尾序号
        int index = str.lastIndexOf(nodeName);
        if (index >= 0) {
            index += nodeName.length();
            return index < str.length() ? str.substring(index) : "";
        }
        return str;
    }

    @Override
    public void close() throws IOException {
        client.close();
    }
}
